<template>
  <view class="pages">
    <view class="tip-staps sticky-header">
        <view class="tip-banner">
            <view class="flexs">
                <image src="/static/audio-icon.png" class="icon" />
                <text class="tip-text">如实填写信息，AI估杆结果更精准</text> 
            </view>
            <view class="tag">
                <image src="/static/light.png" class="light" />
                <image src="/static/lightbulb.png" class="bulb" />
                <image src="/static/light-icon.png" class="light-icon" />
                <text class="tag-text">小贴士</text>
            </view>
        </view>
        <view class="progress-box">
            <aprogress :currentStep="progressPercent" :totalSteps="totalFields" ></aprogress>
        </view> 
    </view>
    
  <view class="page">
    <view class="flex" @click="addPin">
        <text class="flex-left">1. 品牌/名称（型号） <text class="brand">*</text></text>
        <view class="flex-right">
            <text class="flex-right-text"> {{form.brandName}} / {{form.cueName}}</text>
            <img src="/static/right2.png" class="icons-right" />
        </view>
    </view>
    <!-- 台球杆名称 -->
    <!-- <view class="flex">
        <text class="label">1. 台球杆名称 <text class="brand">*</text></text>
        <view class="flex flex-right" @click="showCueNameInput = !showCueNameInput" >
            <text class="label flex-right-text" v-if="!showCueNameInput && form.cueName">{{ form.cueName }}</text>
            <img v-if="!showCueNameInput" src="/static/right2.png" class="icons-right" />
        </view>
    </view>
    <uni-easyinput v-if="showCueNameInput" type="text" @blur="showCueNameInput = !showCueNameInput" v-model="form.cueName" placeholder="例：三国白龙台球杆"  /> -->

    <!-- 台球杆结构 -->
    <view class="flex">
        <text class="label">2. 台球杆结构 <text class="brand">*</text></text>
        <view class="flex flex-right" @click="showCueStrucInput = !showCueStrucInput">
            <text class="label flex-right-text" v-if="!showCueStrucInput && form.cueStruc">{{ form.cueStruc }}</text>
            <img v-if="form.cueStruc" src="/static/right2.png" class="icons-right" />

            <!-- <img @click="showCueStrucInput = !showCueStrucInput" v-if="showCueStrucInput" src="/static/right.png" class="icons" />
            <img @click="showCueStrucInput = !showCueStrucInput" v-else src="/static/down.png" class="icons" /> -->
        </view>
    </view>
    <view class="flex-grid" v-if="showCueStrucInput">
        <view v-for="item in changeList" :key="item.value" class="grid-item" :class="{ active: form.cueStruc === item.value }" @click="setCue(item)">{{ item.text }}</view>
    </view>
    
    <!-- 外观成色 -->
    <view class="flex">
        <text class="label">3. 外观成色 <text class="brand">*</text></text>
        <view class="flex flex-right" @click="showUseLevelInput = !showUseLevelInput">
            <text class="label flex-right-text" v-if="form.useLevel">{{ form.useLevel }}</text>
            <img v-if="form.useLevel" src="/static/right2.png" class="icons-right" />

            <!-- <img @click="showUseLevelInput = !showUseLevelInput" v-if="showUseLevelInput" src="/static/right.png" class="icons" />
            <img @click="showUseLevelInput = !showUseLevelInput" v-else src="/static/down.png" class="icons" /> -->
        </view>
    </view>
    <view class="flex-grid" v-if="showUseLevelInput">
        <view v-for="item in oldList" :key="item.value" class="grid-item" :class="{ active: form.useLevel === item.value }" @click="setLevel(item)">{{ item.text }}</view>
    </view>


    <!-- 是否手工杆 -->
    <view class="flex">
        <text class="label">4. 是否手工杆 <text class="brand">*</text></text>
        <view class="flex flex-right" @click="showIsManuallInput = !showIsManuallInput">
            <text class="label flex-right-text" v-if="!showIsManuallInput && form.isManual">{{ form.isManual }}</text>
            <img v-if="form.isManual" src="/static/right2.png" class="icons-right" />

            <!-- <img @click="showIsManuallInput = !showIsManuallInput" v-if="showIsManuallInput" src="/static/right.png" class="icons" />
            <img @click="showIsManuallInput = !showIsManuallInput" v-else src="/static/down.png" class="icons" /> -->
        </view>
    </view>
    <view class="flex-grid" v-if="showIsManuallInput">
        <view v-for="item in typeList" :key="item.value" class="grid-item" :class="{ active: form.isManual === item.value }" @click="setManual(item)">{{ item.text }}</view>
    </view>

    <!-- 购买时间 -->
     <view class="flex">
        <text class="label">5. 球杆购买时间  <text class="brand">*</text></text>
        <view class="flex flex-right" @click="showPurchaseDate = !showPurchaseDate">
            <text class="label flex-right-text" v-if="!showPurchaseDate && form.purchaseDate">{{ form.purchaseDate }}</text>
            <img v-if="showPurchaseDate == false" src="/static/right2.png" class="icons-right" />

            <!-- <img @click="showPurchaseDate = !showPurchaseDate" v-if="showPurchaseDate" src="/static/right.png" class="icons" />
            <img @click="showPurchaseDate = !showPurchaseDate" v-else src="/static/down.png" class="icons" /> -->
        </view>
    </view>
    <uni-datetime-picker v-if="showPurchaseDate" @change="showPurchaseDate = !showPurchaseDate" type="date" placeholder="请选择购买时间" :clear-icon="false" v-model="form.purchaseDate"  />


    <!-- 购买价格 -->
    <view class="flex">
        <text class="label">6. 球杆购入价  <text class="brand">*</text></text>
        <view class="flex flex-right" @click="showTransactionPrice = !showTransactionPrice">
            <text class="label flex-right-text" v-if="!showTransactionPrice && form.transactionPrice">{{ form.transactionPrice }}</text>
            <img v-if="showTransactionPrice == false" src="/static/right2.png" class="icons-right" />

            <!-- <img @click="showTransactionPrice = !showTransactionPrice" v-if="showTransactionPrice" src="/static/right.png" class="icons" />
            <img @click="showTransactionPrice = !showTransactionPrice" v-else src="/static/down.png" class="icons" /> -->
        </view>
    </view>
    <uni-easyinput v-if="showTransactionPrice" @blur="setPrice" type="text" v-model="form.transactionPrice" placeholder="例：15800元" />


    <!-- 上传图片 -->
    <view class="flex">
        <text class="label">7. 球杆图片  <text class="brand">*</text></text>
        <!-- <view class="flex flex-right" @click="showImages = !showImages">
        <img src="/static/right2.png" class="icons-right" />
        </view> -->
    </view>
    <view class="example-body" v-show="showImages">
        <uni-file-picker 
            v-model="imageValue" 
            file-mediatype="image" 
            file-extname="png,jpg" 
            mode="grid" 
            :limit="5" 
            title="最多选择5张图片"
            @select="handleSelect"
        ></uni-file-picker>
    </view>

    <!-- 描述 -->
    <view class="flex">
        <text class="label">8. 补充描述 </text>
        <!-- <view class="flex flex-right" @click="showAddedValue = !showAddedValue">
             <img src="/static/right2.png" class="icons-right" />
        </view> -->
    </view>
    <uni-easyinput v-if="showAddedValue" @blur="showAddedValue = !showAddedValue" type="textarea" v-model="form.addedValue" placeholder="例：杆盒/配件/防伪。请勿输入不真实信息，以免影响估值"  />
  </view>

  <view class="parent">
    <!-- 提交按钮 -->
    <button class="submit-btn" @click="submit">去估杆 →</button>
  </view>
    
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app' 
import { ref, watch } from 'vue'
import { request,uploadFiles  } from '../utils/request'
const imageValue = ref([]) // 绑定已选择文件列表
const localImagePaths = ref([]) // 存储临时地址

const form = ref({
    brandName: '', // 品牌名称
    cueName: '', // 台球杆名称
    cueStruc: '', // 台球杆结构
    useLevel: '', // 外观成色
    isManual: '', // 是否手工杆
    purchaseDate: '', // 购买时间
    transactionPrice: '', // 购买价格
    addedValue: '' // 附加值
})

watch(
  [form.value, localImagePaths],
  () => {
    progressPercent.value = computeProgress()
  },
  { deep: true }
)
const showCueNameInput = ref(true) 
const showCueStrucInput = ref(true)
const showUseLevelInput = ref(true)
const showIsManuallInput = ref(true)
const showPurchaseDate = ref(true)
const showTransactionPrice = ref(true)
const showImages = ref(true)
const showAddedValue = ref(true)
const progressPercent = ref(0) // 进度百分比
const totalFields = ref(7) // 需填写的字段总数

const changeList = [
    { value: "一体通杆", text: "一体通杆" },
    { value: "分体杆", text: "分体杆" },
]
const oldList = [
    { value: "全新未使用", text: "全新未使用" },
    { value: "99新", text: "99新" },
    { value: "95新", text: "95新" },
    { value:  "9新", text: "9新" },
    { value: "8新", text: "8新" },
    { value: '8新以下', text: '8新以下' }
]
const computeProgress = () => {
  let filled = 0
  if (form.value.brandName && form.value.cueName) filled++
  if (form.value.cueStruc != '') filled++
  if (form.value.useLevel != '') filled++
  if (form.value.isManual != '') filled++
  if (form.value.purchaseDate != '') filled++
  if (form.value.transactionPrice != '') filled++
  if (localImagePaths.value.length > 0) filled++
  return filled
//   return Math.round((filled / totalFields.value) * 100)
}
const typeList = [
    { value: "是", text: "是" },
    { value: "否", text: "否" },
]
const validateForm = () => {
  const fields = [
    { key: 'brandName', label: '品牌名称' },
    { key: 'cueName', label: '台球杆名称' },
    { key: 'cueStruc', label: '台球杆结构' },
    { key: 'useLevel', label: '外观成色' },
    { key: 'isManual', label: '是否手工杆' },
    { key: 'purchaseDate', label: '球杆购买时间' },
    { key: 'transactionPrice', label: '球杆购入价' },
  ]

  for (const field of fields) {
    if (!form.value[field.key]) {
      uni.showToast({
        title: `请填写${field.label}`,
        icon: 'none'
      })
      return false
    }
  }
  if(localImagePaths.value.length == 0){
    uni.showToast({
        title: `请上传${'球杆图片'}`,
        icon: 'none'
    })
    return false
  }

  return true
}
const setCue = (item) => {
    form.value.cueStruc = item.value
    showCueStrucInput.value = false // 选择后关闭下拉
}
const setLevel = (item) => {
  form.value.useLevel = item.value
  showUseLevelInput.value = false // 选择后关闭下拉
}
const setManual = (item) => {
    form.value.isManual = item.value
    showIsManuallInput.value = false // 选择后关闭下拉
}
const setPrice = () => {
    if(form.value.transactionPrice) {
        showTransactionPrice.value = !showTransactionPrice
    }
}

const submit = async() => {
    if (!validateForm()) return
    uni.showLoading({ title: '提交中...' })
    try {
        const newForm = {
            ...form.value,
            brandName: form.value.brandName.split('/')[0]
        }

        await request({
        url: '/user/assess/submit',
        method: 'POST',
        data: newForm
    })
        .then(async (res) => {
            if (res.code === 200) {
                const id = res.data
                const uploadTasks = localImagePaths.value.map((item, index) => {
                    console.log('上传文件:', index == 0 ? 'true' : 'false')
                    return uploadFiles({
                        url: `/user/assess/upload/${id}`,
                        filePath: item.tempFilePath,
                        name: 'file',
                        formData: {
                            id,
                            cover: index == 0 ? 'true' : 'false',
                            file: item
                        },
                        header: {
                            'Content-Type': 'multipart/form-data'
                        }
                    })
                })
                // 等待所有上传完成
                await Promise.all(uploadTasks);
                uni.hideLoading()
                uni.showToast({ title: '提交成功', icon: 'success', duration: 3000})
                form.value = {
                    brandName: '',
                    cueName: '',
                    cueStruc: '',
                    useLevel: '',
                    transactionPrice: '',
                    purchaseDate: '',
                    isManual: '',
                    addedValue: ''
                }
                localImagePaths.value = []
                imageValue.value = []
                uni.navigateTo({
                    url: '/pages/index/result?id=' + id
                })
            } else {
                uni.showToast({ title: res.data.message || '提交失败', icon: 'none', duration: 3000  })
            }
        }).catch((err) => {
            console.error('请求失败:', err)
            uni.showToast({ title: err.data.message || '提交失败', icon: 'none', duration: 3000  })
        })
    } catch (err) {
        console.log('验证失败', err);
        uni.hideLoading()
    } finally {
        uni.hideLoading()
    }
}

const handleSelect = (e) => {
    // 提取临时地址
    localImagePaths.value = e.tempFiles.map(file => file.file)
    console.log('临时地址数组:', localImagePaths.value)
}
const addPin = () => {
    uni.navigateTo({
        url: '/pages/index/project'
    })
}
onLoad((query) => {
    setTimeout(() => {
        const name = decodeURIComponent(query.name || '')
        form.value.brandName = name.split('/')[0] || ''// 只取品牌名称
        form.value.cueName = name.split('/')[1] || '' // 取台球杆名称

    },100)
})
</script>

<style scoped>
.sticky-header {
  position: sticky;
  top: 0;
  z-index: 999;
  background-color: #ffffff;
  height: 150rpx;
}

/* 可选的边框/阴影提升效果 */
.sticky-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 0px;
  background: #eee;
}
.tip-banner {
  background-color: #fff7e8;
  padding: 16rpx;
  display: flex;
  align-items: center;
  border-radius: 12rpx;
  position: relative;
}
.progress-box{
    margin: 16rpx 20rpx 28rpx;
}

.icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;
}
.icons-right{
    width: 13rpx;
    height: 21rpx;
    margin-top: 10rpx;
}
.tip-text {
  flex: 1;
  color: #FAAD14;
  font-size: 24rpx;
}

.tag {
  display: flex;
  align-items: center;
  position: relative;
  margin-left: 20rpx;
}
.light {
    height: 40rpx;
    width: 124rpx;
}
.bulb {
  width: 60rpx;
  height: 60rpx;
  position: absolute;
  right: -25rpx;
}
.light-icon{
    position: absolute;
    right: -18rpx;
    top: -5px;
    width: 15rpx;
    height: 18rpx;
}
.tag-text {
    color: #fff;
    font-size: 24rpx;
    position: absolute;
    font-family: DingTalk JinBuTi;
    left: 30rpx;
}

.label {
  font-weight: bold;
  margin-top: 30rpx;
  margin-bottom: 20rpx;
  display: block;
}
.parent {
  display: flex;
  justify-content: center;
}
.submit-btn {
  background: linear-gradient(to right, #45b5ff, #2b65f6);
  color: white;
  display: inline-block;
  margin: 40rpx auto;
  width: 500rpx;
  height: 90rpx;
  border-radius: 10rpx;
}
.page{
    padding: 0 20rpx;
}
.flex{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
    font-size: 30rpx;
}
.flexs {
    display: flex;
    align-items: center;
}
.flex-left{
    font-weight: bold;
}
.brand{
    color: red;
}
.flex-right{
    color: #999;
    margin-bottom: 10rpx;
}
.flex-right-text{
    margin-right: 16rpx;
}
.flex-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
}
.grid-item {
    background-color: #f5f5f5;
    padding: 20rpx;
    text-align: center;
    border-radius: 60rpx;
    /* margin: 20rpx 0; */
    border: 1px solid #eeeeee;
}
.active{
    border-color: #007aff;
    color: #007aff;
    background-color: rgba(0, 122, 255, .1);
}
.icons{
    width: 28rpx;
    height: 28rpx;
}
</style>
